package joshua.web.utils;

import java.lang.reflect.InvocationTargetException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import joshua.web.beans.BeanManager;

import org.apache.commons.beanutils.BeanUtils;

public class MyBeanUtils {
	public static <T> T populateBeanFromReq(HttpServletRequest request, Class<T> type) {
		T bean = BeanManager.getBean(type);
		Enumeration names = request.getParameterNames();
		Map<String, String> properties = new HashMap<String, String>();
		while(names.hasMoreElements()) {
			String name = (String)names.nextElement();
			String value = request.getParameter(name);
			properties.put(name, value);
		}
		try {
			BeanUtils.populate(bean, properties);
		} catch(IllegalAccessException e) {
			e.printStackTrace();
			return null;
		} catch (InvocationTargetException e) {
			e.printStackTrace();
			return null;
		}
		return bean;

	}
}
